<template>
  <el-dialog title="修改用户昵称" v-model="props.visible" @close="close" width="500px">
    <el-divider />
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="auto" status-icon>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
      </el-form-item>
    </el-form>
    <el-divider />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { userUpdateBase } from "@/api/user";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object,
    default: () => { }
  }
});

const emit = defineEmits(['close', 'submit']);
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
  ],
});

const formData = ref({
  nickname: "", // 用户昵称
});

// 
const close = () => {
  emit('close', false);
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      userUpdateBase({
        id: props.userInfo.id,
        field_name: "nickname",
        value: formData.value.nickname
      }).then((res: any) => {
        close();
        if (res.code === 200) {
          ElMessage.success('修改成功!');
          emit('submit');
        }
      });
    }
  })
};

onMounted(() => {
  if (JSON.stringify(props.userInfo) !== "{}") {
    formData.value.nickname = props.userInfo.nickname;
  }
});
</script>

<style></style>
